// 商品分库管理
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, message, Modal } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { text_check, post_axios, key_find_obj } from "../../utils";

export default function Kind(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { confirm } = Modal;
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";
  const visual_cabinet_group = [
    {
      value: "",
      key: "",
      label: text_check({
        msg_cn: "不支持",
        msg_en: "nonsupport",
      }),
    },
    {
      value: "cloud_walk",
      key: "cloud_walk",
      label: text_check({
        msg_cn: "云从视觉柜",
        msg_en: "cloud_walk",
      }),
    },
    {
      value: "alipay_lite",
      key: "alipay_lite",
      label: text_check({
        msg_cn: "支付宝lite动态视觉柜",
        msg_en: "alipay_lite",
      }),
    },
    {
      value: "alipay_cloud",
      key: "alipay_cloud",
      label: text_check({
        msg_cn: "支付宝+云从",
        msg_en: "alipay_cloud",
      }),
    },
  ];

  const [goods_kind_list, setGoods_kind_list] = useState([]);

  const getData = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("goods_kind_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setGoods_kind_list(res.data_rows.rows);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("goods.sub_treasury_label"),
      dataIndex: "kind",
      align: "center",
    },
    {
      title: t("goods.sub_treasury_name"),
      dataIndex: "name",
      align: "center",
    },
    {
      title: "视觉柜",
      align: "center",
      render: (_, record) => (
        <>
          {record.goods_vision_type && record.goods_vision_type !== "" ? (
            <span style={{ fontWeight: "600" }}>
              {
                key_find_obj(
                  record.goods_vision_type,
                  visual_cabinet_group,
                  "value"
                ).label
              }
            </span>
          ) : (
            <span style={{ color: "#ccc" }}>不支持</span>
          )}
        </>
      ),
    },
  ];

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.kind);
    setclickRow(row);
  };

  const search_data = () => {
    initData();
  };

  const initData = () => {
    setClickRowKey("");
    setclickRow([]);
    getData();
  };

  // 添加/修改
  const [edit_type, setEdit_type] = useState("");
  const [editDialogshow, setEditDialogshow] = useState(false);
  const [editDialogtitle, setEditDialogtitle] = useState("");

  const [edit_goods_name, setEdit_goods_name] = useState("");
  const [edit_goods_kind, setEdit_goods_kind] = useState("");
  const [visual_cabinet_support, setVisual_cabinet_support] = useState("");

  const edit_customer_dialog_show = async (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEditDialogshow(true);
      setEditDialogtitle(t("common.add"));
      setEdit_goods_name("");
      setEdit_goods_kind(1);
      setVisual_cabinet_support("");
    } else {
      if (clickRowKey === "") {
        message.warning({
          content: t("market.select_mch"),
        });
        return;
      }
      setEditDialogshow(true);
      setEditDialogtitle(t("common.change"));
      const { name, kind, goods_vision_type } = clickRow;

      setEdit_goods_name(name);
      setEdit_goods_kind(kind);
      setVisual_cabinet_support(goods_vision_type);
    }
  };

  const editConfirm = async () => {
    if (edit_goods_name === "") {
      message.warning({
        content: t("goods.enter_sub_treasury_name"),
      });
      return;
    }
    let upMsg = {
      name: edit_goods_name,
      kind: edit_goods_kind,
      goods_vision_type: visual_cabinet_support,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add";
    if (edit_type == "change") {
      action = "m_modify";
    }
    setSpinning(true);
    let res = await post_axios("goods_kind_manager", action, upMsg);
    if (!res) return;
    setSpinning(false);
    if (!res) return;
    message.success({
      content: editDialogtitle + " " + t("common.successfully"),
    });
    setEditDialogshow(false);
    search_data();
  };

  const delete_kind = () => {
    if (clickRowKey === "") {
      message.warning({
        content: t("goods.choose_sub_treasury"),
      });
      return;
    }
    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          {t("goods.sure_to_delete_sub_treasury")}
          <strong> {clickRow.name}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          name: clickRow.name,
          kind: clickRow.kind,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        setSpinning(true)
        let res = await post_axios("goods_kind_manager", "m_del", upMsg);
        setSpinning(false)
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("goods_kind_manager")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 40 - 30;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="goods_kind_manager modules">
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_customer_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_customer_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_kind}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="noPage-table"
            style={{
              width: "99.9vw",
            }}
          >
            <Table
              dataSource={goods_kind_list}
              size="small"
              bordered
              columns={columns}
              rowKey="kind"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.kind == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>
        </div>
      </div>

      <Modal
        title={editDialogtitle}
        open={editDialogshow}
        onOk={editConfirm}
        onCancel={() => setEditDialogshow(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">{t("goods.sub_treasury_name")}</div>
          <Input
            placeholder=" "
            value={edit_goods_name}
            onChange={(e) => setEdit_goods_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box dialog_ipt_box_long normal_title">
          <div className="ipt_box_title">{t("common.status")}</div>
          <Select
            placeholder=" "
            allowClear={false}
            options={visual_cabinet_group}
            value={visual_cabinet_support}
            disabled={edit_type === 'change'}
            onChange={(value) => setVisual_cabinet_support(value)}
          />
        </div>
      </Modal>
    </>
  );
}
